package spaceshop

import (
	"strconv"

	"strings"

	"github.com/astaxie/beego/orm"
)

var kmjxcSubNumbers map[string]*KmjxcSubNumber

func init() {
	orm.RegisterModel(new(KmjxcSubNumber))
}

type KmjxcSubNumber struct {
	ID    int `orm:"pk;column(ID)"`
	Name  string
	SubNo int
}

type IKmjxcSubNumbersManager interface {
	GetSubNumberName() string
	GetPrefix() string
}

type KmjxcSubNumbersManager struct {
	numbers    map[string]*KmjxcSubNumber
	NumberName string
	GetPrefix  func() string
}

//initSubNumbers kmjxc_sub_number
func initSubNumbers() {
	o := orm.NewOrm()
	r := o.Raw(`select * from kmjxc_sub_numbers`)
	var subNos []*KmjxcSubNumber
	if _, err := r.QueryRows(&subNos); err == nil {
		kmjxcSubNumbers = make(map[string]*KmjxcSubNumber)
		for _, sN := range subNos {
			//每取值一次自增1
			sN.SubNo++
			kmjxcSubNumbers[sN.Name] = sN
		}
	}
}

func NewKmjxcSubNumberManager(numberName string, getPrefix func() string) *KmjxcSubNumbersManager {
	initSubNumbers()
	ksnm := &KmjxcSubNumbersManager{
		numbers:    kmjxcSubNumbers,
		NumberName: numberName,
		GetPrefix:  getPrefix,
	}
	return ksnm
}

func (ksnm *KmjxcSubNumbersManager) GetSubNo(dep string) string {
	var idPref string
	ksn := ksnm.numbers[ksnm.NumberName]
	if ksn.SubNo < 10 {
		idPref = "000"
	} else if ksn.SubNo < 100 {
		idPref = "00"
	} else if ksn.SubNo < 1000 {
		idPref = "0"
	} else if ksn.SubNo < 10000 {
		idPref = ""
	} else {
		//当10000时变1重新增量
		ksn.SubNo = 1
		idPref = "000"
	}
	//取值
	ids := strconv.Itoa(ksn.SubNo)
	//取值后自增保存
	o := orm.NewOrm()
	r := o.Raw(`update kmjxc_sub_numbers set sub_no = ` + strconv.Itoa(ksn.SubNo) + ` where name= "` + ksnm.NumberName + `"`)
	if _, err := r.Exec(); err == nil {
		ksn.SubNo++
	} else {
		panic(err)
	}
	return strings.Replace(ksnm.GetPrefix(), "?", dep, 1) + idPref + ids

}
